package com.oinux.playhelper.ui;

import java.sql.SQLException;
import java.util.List;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.dao.RawRowMapper;
import com.oinux.playhelper.R;
import com.oinux.playhelper.app.BaseActivity;
import com.oinux.playhelper.db.DatabaseHelper;
import com.oinux.playhelper.entity.AppInfo;
import com.oinux.playhelper.util.ScreenShot;
import com.oinux.playhelper.util.TimeUtils;
import com.oinux.playhelper.widget.ChartBar;
import com.oinux.playhelper.widget.YesOrNoDialog;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.UMSsoHandler;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.TencentWBSsoHandler;

public class AppStatistics extends BaseActivity implements OnClickListener {

	private TextView titleText;
	private TextView totalAppText;
	private TextView chartNameText;
	private Button shareBtn;
	private Button crashBtn;
	private LinearLayout chartView;

	private DatabaseHelper databaseHelper = null;
	private long total;
	private String imagePath;
	
	final UMSocialService mController = UMServiceFactory.getUMSocialService(
			"com.umeng.share", RequestType.SOCIAL);


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.app_statistics);
		initView();
		initData();
		initShare();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(
				requestCode);
		if (ssoHandler != null) {
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}
	
	private void initShare() {
		mController.getConfig().removePlatform(SHARE_MEDIA.EMAIL,
				SHARE_MEDIA.SMS);
		/** 微信支持 **/
		String appID = "wx83c398197a1722cd";
		String contentUrl = "http://www.oinux.com:8080/static/playhelper/index.html";
		mController.getConfig().supportWXPlatform(this, appID, contentUrl);
		mController.getConfig()
				.supportWXCirclePlatform(this, appID, contentUrl);
		/** QQ支持 **/
		mController.getConfig().supportQQPlatform(this,
				"http://www.oinux.com:8080/static/playhelper/index.html");
		/** SSO登陆 **/
		mController.getConfig().setSsoHandler(new QZoneSsoHandler(this));
		mController.getConfig().setSsoHandler(new SinaSsoHandler());
		mController.getConfig().setSsoHandler(new TencentWBSsoHandler());
	}
	
	private void setShare() {
		mController.setShareContent("这是我通过“玩手机助手”记录所有应用运行时间统计图，小伙伴们也快去试试吧，下载地址：http://www.oinux.com:8080/static/playhelper/index.html");
		mController.setShareMedia(new UMImage(this, BitmapFactory
				.decodeFile(imagePath)));
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (databaseHelper != null) {
			OpenHelperManager.releaseHelper();
			databaseHelper = null;
		}
	}

	private DatabaseHelper getHelper() {
		if (databaseHelper == null) {
			databaseHelper = OpenHelperManager.getHelper(this,
					DatabaseHelper.class);
		}
		return databaseHelper;
	}

	private void initData() {
		GenericRawResults<AppInfo> rawResults = null;
		List<AppInfo> appInfos = null;
		String sql = "select id, name, totalTime+runTime totalTime from app_info order by totalTime desc limit 0, 9";
		try {
			rawResults = getHelper().getAppInfoDao().queryRaw(sql,
					new RawRowMapper<AppInfo>() {
						public AppInfo mapRow(String[] columnNames,
								String[] resultColumns) {
							return new AppInfo(Integer
									.parseInt(resultColumns[0]),
									resultColumns[1], Long
											.parseLong(resultColumns[2]));
						}
					});
			appInfos = rawResults.getResults();
			total = getHelper().getAppInfoDao().countOf();
			long divider = TimeUtils.DIVIDE_TO_MINUTES;
			long maxTime = 0;
			if (appInfos.size() > 0)
				maxTime = appInfos.get(0).getTotalTime();

			if ((maxTime / 100) > TimeUtils.DIVIDE_TO_YEAR)
				divider = TimeUtils.DIVIDE_TO_YEAR;
			else if ((maxTime / 100) > TimeUtils.DIVIDE_TO_MONTH)
				divider = TimeUtils.DIVIDE_TO_MONTH;
			else if ((maxTime / 100) > TimeUtils.DIVIDE_TO_DAY)
				divider = TimeUtils.DIVIDE_TO_DAY;
			else if ((maxTime / 100) > TimeUtils.DIVIDE_TO_HOUR)
				divider = TimeUtils.DIVIDE_TO_HOUR;
			int max = (int) (maxTime / divider * 1.2);
			chartView.removeAllViews();
			for (int i = 0; i < appInfos.size(); i++) {
				final AppInfo appInfo = appInfos.get(i);
				View item = getLayoutInflater().inflate(
						R.layout.bar_chart_item, null);
				TextView appName = (TextView) item.findViewById(R.id.app_name);
				ChartBar appChart = (ChartBar) item
						.findViewById(R.id.app_chart);
				appChart.setMax(max);
				appChart.setProgress((int) (appInfo.getTotalTime() / divider));
				appName.setText(appInfo.getName());
				item.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(AppStatistics.this,
								AppDetail.class);
						intent.putExtra("app_id", appInfo.getId());
						startActivity(intent);
					}
				});
				chartView.addView(item);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rawResults != null)
					rawResults.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		totalAppText.setText(total + "个应用");
		chartNameText.setText("运行时间最多的9个应用");
	}

	private void initView() {
		titleText = (TextView) findViewById(R.id.title_bar_text);
		titleText.setText(R.string.app_statistics);
		totalAppText = (TextView) findViewById(R.id.total_app_text);
		chartNameText = (TextView) findViewById(R.id.chart_name);
		shareBtn = (Button) findViewById(R.id.share_btn);
		shareBtn.setOnClickListener(this);
		crashBtn = (Button) findViewById(R.id.crash_app_btn);
		crashBtn.setOnClickListener(this);
		chartView = (LinearLayout) findViewById(R.id.chart);
	}

	@Override
	public void onClick(View v) {
		if (v == shareBtn) {
			String state = Environment.getExternalStorageState();
			if (Environment.MEDIA_MOUNTED.equals(state)) {
				imagePath = ScreenShot.shoot(this);
				setShare();
				mController.openShare(this, false);
			} else {
				Toast.makeText(this, "SD卡未挂载，不能截图", Toast.LENGTH_SHORT).show();
			}
		} else if (v == crashBtn) {
			YesOrNoDialog.Builder builder = new YesOrNoDialog.Builder(this);
			builder.setMessage(R.string.crash_tip).setTitle(R.string.crash);
			builder.setNegativeButton(R.string.no,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.setPositiveButton(R.string.yes,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							appContext.crash();
							initData();
						}
					});
			builder.create().show();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
}